package com.cloud.tsp.controller;

import com.cloud.api.domain.service.*;
import com.cloud.core.exception.MyException;
import com.cloud.core.util.R;
import com.cloud.log.annotation.Log;
import com.cloud.log.enums.BusinessType;
import com.cloud.log.enums.OperatorType;
import com.cloud.tsp.config.DateUtils;
import com.cloud.tsp.service.CertificateService;
import com.cloud.tsp.service.IContactHistoryService;
import com.cloud.tsp.service.IStationServiceBaseInfoService;
import com.xingyuv.captcha.model.common.ResponseModel;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Base64;

/**
 * @author 杨斌
 * 2025-03-2025-03-10
 */
@RestController
@RequestMapping("/contact")
@Slf4j
public class ContactController {
    @Resource
    private IContactHistoryService contactHistoryService;

    @Resource
    private CertificateService certificateService;

    @Resource
    private CaptchaService captchaService;

    @Resource
    private IStationServiceBaseInfoService stationServiceBaseInfoService;


    @Tag(name = "v1.0")
    @Operation(summary = "获取验证码")
    @PostMapping("/getCaptcha")
    @Log(title = "获取验证码", businessType = BusinessType.OTHER, operatorType = OperatorType.MANAGE)
    public R getCaptcha(@RequestBody @Valid CaptchaVO data) {
        ResponseModel responseModel = captchaService.get(data);
        return R.ok(responseModel.getRepData());
    }

    @Tag(name = "v1.0")
    @Operation(summary = "核对图形验证码")
    @PostMapping("/check")
    @Log(title = "核对图形验证码", businessType = BusinessType.OTHER, operatorType = OperatorType.MANAGE)
    public R check(@RequestBody CaptchaVO data) {
        ResponseModel responseModel = captchaService.check(data);
        CaptchaVO repData = (CaptchaVO) responseModel.getRepData();
        if (repData == null || Boolean.FALSE.equals(repData.getResult())) {
            throw new MyException("wds.exception.verificationImageFailed", 20000);
        }
        return R.ok(responseModel.getRepData());
    }

    @Tag(name = "v1.0")
    @Operation(summary = "更换联系方式")
    @PostMapping("/updateContact")
    @Log(title = "更换联系方式", businessType = BusinessType.OTHER, operatorType = OperatorType.MANAGE)
    public R updateContact(@RequestBody @Valid UpdateContactRequest para) {
        // 获取图形验证码相关信息
        CaptchaVO captchaVO = para.getCaptchaVO();
        if(captchaVO == null){
            throw new MyException("wds.exception.verificationImageError", 20001);
        }
        // 进行图形验证码的二次校验
        ResponseModel responseModel = captchaService.verification(captchaVO);
        // 检查验证码校验是否成功
        if (responseModel.isSuccess() && "成功".equals(responseModel.getRepMsg())) {
            // 验证码校验成功，调用 updateContact 方法更新联系方式
            return contactHistoryService.updateContact(para);
        } else {
            String repMsg = responseModel.getRepMsg();
            return R.failed(repMsg);
        }
    }
    @Tag(name = "v1.0")
    @Operation(summary = "运营授权书下载")
    @PostMapping("/downloadAuthorization")
    @Log(title = "运营授权书下载", businessType = BusinessType.OTHER, operatorType = OperatorType.MANAGE)
    public R<String> downloadAuthorization (@RequestBody @Valid QueryAuthorization para) {
        // 获取图形验证码相关信息
        CaptchaVO captchaVO = para.getCaptchaVO();
        if(captchaVO == null){
            throw new MyException("wds.exception.verificationImageError", 20001);
        }
        // 进行图形验证码的二次校验
        ResponseModel responseModel = captchaService.verification(captchaVO);
        // 检查验证码校验是否成功
        if (responseModel.isSuccess() && "成功".equals(responseModel.getRepMsg())) {
            // 验证码校验成功，下载运营授权
            return stationServiceBaseInfoService.downloadAuthorization(para);
        } else {
            String repMsg = responseModel.getRepMsg();
            return R.failed(repMsg);
        }
    }
    @Tag(name = "v1.0")
    @Operation(summary = "获取修改信息")
    @PostMapping("/getContactAudit")
    @Log(title = "信息修改", businessType = BusinessType.OTHER, operatorType = OperatorType.MANAGE)
    public R<ServiceStationInfo> getContactInformation () {

        return R.ok(contactHistoryService.getContactInformation());
    }

    @Tag(name = "v1.0")
    @Operation(summary = "信息修改审核")
    @PostMapping("/auditContact")
    @Log(title = "信息修改审核", businessType = BusinessType.OTHER, operatorType = OperatorType.MANAGE)
    public R auditContact (@RequestBody @Valid AuditRequest para) {
        return contactHistoryService.auditContact(para);

    }

//    @PostMapping("/generate")
//    public ResponseEntity<byte[]> generateCertificate(@RequestBody CertificateRequest request) {
//        request.setCurrentDate(DateUtils.formatDateToChinese(LocalDate.now()));
//        byte[] pdf = new byte[0];
//        try {
//            pdf = certificateService.generatePdf(request);
//        } catch (IOException e) {
//            throw new MyException("生成pdf 失败");
//        }
//
//        if (pdf == null || pdf.length == 0) {
//            throw new MyException("生成pdf 失败");
//        }
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_PDF);
//        headers.setContentDispositionFormData("attachment", "certificate.pdf");
//
//        return new ResponseEntity<>(pdf, headers, HttpStatus.OK);
//    }

    @Tag(name = "v1.0")
    @Operation(summary = "编辑证书预览")
    @PostMapping("/generate")
    @Log(title = "编辑证书预览", businessType = BusinessType.OTHER, operatorType = OperatorType.MANAGE)
    public R<String> generateCertificate(@RequestBody CertificateRequest request) {
        request.setSignDate(DateUtils.toChineseDate(request.getSignDate()));
        byte[] pdf = new byte[0];
        try {
            pdf = certificateService.generatePdf(request);
        } catch (IOException e) {
            throw new MyException("生成pdf 失败");
        }

        if (pdf == null || pdf.length == 0) {
            throw new MyException("生成pdf 失败");
        }
        // 将 PDF 数据转换为 Base64 编码
        String base64Pdf = Base64.getEncoder().encodeToString(pdf);

        return R.ok(base64Pdf);
    }
    @Tag(name = "v1.0")
    @Operation(summary = "详情证书预览")
    @PostMapping("/getCertificate")
    @Log(title = "详情证书预览", businessType = BusinessType.OTHER, operatorType = OperatorType.MANAGE)
    public R<String> generateCertInfos(@RequestBody CertificateInfos para) {
        return stationServiceBaseInfoService.generateCertInfos(para);
    }

}
